/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package src.view.loan;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import org.primefaces.context.RequestContext;
import org.primefaces.event.CloseEvent;
import src.domain.loan.Loan;
import src.domain.loan.Loandd;
import src.domain.security.Users;
import src.domain.system.Numbering;
import src.services.CRUEDService;
import src.services.loan.CollateralModel;
import src.services.loan.LoanModel;
import src.services.loan.LoanddModel;
import src.util.Constanta;
import src.util.Messager;
import src.util.Utils;
import src.view.security.LoginBean;

/**
 *
 * @author jay
 * ontohod teh
 */
@ManagedBean
@SessionScoped
public class LoanddBean implements Serializable {

    private Loandd loandd;  
    private List<SelectItem> avblCoral;
    private boolean editMode = false, insertionMode=false, authorized=false;
    private String defaultButton="doNothingLoandd";
    private boolean showLookup=false;
    private BigDecimal fee, owing; 
    private Users user;
    
    public LoanddBean() {
        super();
        ambilUser();
        newData();
        editMode = false;
        authorized = false;
    }
    
    public boolean isEditMode() {
        return editMode;
    }
    
    public Loandd getLoandd() {
        return loandd;
    }

    public void setLoandd(Loandd loandd) {
        this.loandd = loandd;
    }

    public List<SelectItem> getAvblCoral() {
        return avblCoral;
    }

    public BigDecimal getFee() {
        return fee;
    }

    public BigDecimal getOwing() {
        return owing;
    }
    
    public String selectItemValueOf(Integer id) {
        return (String) Utils.selectItemValueOf(avblCoral, id);
    }

    public void getLoan(String accntNo) {
        boolean found=false;
        if ("null".equals(accntNo)) accntNo = loandd.getLoan().getLoanNo();
       // String accntNo = loandd.getLoan().getLoanNo();
        
        if (accntNo!=null ) {
            LoanModel helper = new LoanModel();
            Loan loan = helper.getByAccount(accntNo, Constanta.LOANSTATUS_APPROVED);
                        
            if (loan==null) {
                Messager.showWarning("accntNotFound");
                this.loandd.setLoan(new Loan());
                this.fee = BigDecimal.ZERO;
                this.owing = BigDecimal.ZERO;
                
            } else {
                found=true;
                this.loandd.setLoan(loan);
                this.fee = BigDecimal.ZERO;
                for (int i=0; i<loan.getLoancosts().size(); i++) {
                    this.fee = this.fee.add(loan.getLoancosts().get(i).getFeeAmount());
                }
                this.owing = loan.getPrincipalAmount().subtract(fee);
            }
        }
        RequestContext.getCurrentInstance().addCallbackParam("success", found); 
    }
    
    public void search() {}
        
    private void initForm() {
        this.editMode = true;
        this.showLookup=false;
        this.authorized = true;
        this.fee = BigDecimal.ZERO;
        this.owing = BigDecimal.ZERO;
    }
        
    private String newNumber() {
        Numbering currentNo = new CRUEDService().getNextTrxNumber(4, 0, 0, 1);
        return currentNo.getTrxNum();
    }
    
    public final void newData() {  
        initForm();
        if (this.loandd!=null) loandd = null;
        this.loandd = new Loandd();
        insertionMode = true;
    }
    
    public void openData() {
        initForm();
        avblCoral = new CollateralModel().listAll();
        insertionMode = false;
    }
        
    private void validateLimit() {
        BigDecimal ddAmount = loandd.getLoan().getPrincipalAmount();
        BigDecimal ddAmountAlowed = user.getUgroup().getLoanMaxDisb();
        
        this.authorized = ddAmount.compareTo(ddAmountAlowed) >= 0 ? false : true;
    }
    
    public void save() {
        LoanddModel helper = new LoanddModel();
        boolean success; 
        
        validateLimit();  
        
        if (authorized==true) loandd.setDdNo(newNumber());
        
        success = helper.saveData(authorized, loandd);
//                     
//        // re-insert
//        if (!success && insertionMode) loandd.setLoanddId(null);
//        else insertionMode = false;
//        
        this.editMode = (!success);
        
        Messager.showSaveUpdateStatus(success);     
                      
        
        if (!authorized && success)
            Messager.showWarning("unauthorized");    
        
        //ngahaja. biar inputBox bisa ngisi klo eror
        if (!success) authorized = true;
        else {
            
            //kalo sukses & athorized....
            if (authorized) authorized = false;
        } 
        
        // re-insert
        if (!success && insertionMode) loandd.setLoanddId(null);
        else insertionMode = false;
        
        
        RequestContext.getCurrentInstance().addCallbackParam("success", success);  
    }
    
    public void delete() {
           
    }

    public String getDefaultButton() {
        return defaultButton;
    }

    public void setDefaultButton(String defaultButton) {
        this.defaultButton = defaultButton;
    }

    public boolean isShowLookup() {
        return showLookup;
    }

    public void setShowLookup(boolean showLookup) {
        this.showLookup = showLookup;
    }
       
    public void handleCloseLookup(CloseEvent event) {
        this.showLookup=false;
    }

    public boolean isAuthorized() {
        return authorized;
    }

    public Users getUser() {
        return user;
    }

    public void setUser(Users user) {
        this.user = user;
    }
        
    private void ambilUser() {
        FacesContext context = FacesContext.getCurrentInstance();
        LoginBean logBean = (LoginBean) context.getApplication().evaluateExpressionGet(context, "#{loginBean}", LoginBean.class);
        this.user = logBean.getSelectedUser();
    }
}
